//
//  RXNetworkTool.swift
//  weibo
//
//  Created by uncle-R on 15/12/18.
//  Copyright © 2015年 uncle-R. All rights reserved.
//

import UIKit
import AFNetworking


class RXNetworkTool:  AFHTTPSessionManager{
    
    static let sharedInsatance :RXNetworkTool = {
        
        let baseURl1 = NSURL(string: "https://api.weibo.com/")
        
        let tools = RXNetworkTool(baseURL: baseURl1, sessionConfiguration: nil)
        //添加响应的序列化器
           tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
//
//    init() {
//        
//        let baseRUL = "https://api.weibo.com/"
//        super.init(baseURL: NSURL(string: baseRUL), sessionConfiguration: nil)
//        
//    }
//
//    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
//    }
    
    
    //https://api.weibo.com/oauth2/authorize?client_id=758035159&redirect_uri=http://www.baidu.com/
  //重定义类型
    typealias NetworkCallback = (result: [String : AnyObject]?,error: NSError?)-> ()
    //设置登录相关的参数
    //App Key：758035159
    //App Secret：e1e3cdaed0c2da4055333d7c41c8de5a
    private let client_id = "758035159"
            let redirect_uri = "http://www.baidu.com/"
    private let client_secret = "e1e3cdaed0c2da4055333d7c41c8de5a"
    
    //拼接请求链接
    func OauthURL() ->NSURL{
        
        let baseStr = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        return NSURL(string: baseStr)!
    }
    
    
    
    
    //加载accessToken 需要参数 : code  信息用闭包返回
    func loadAccessToken(code: String,finished:NetworkCallback){
        
        let urlString = "oauth2/access_token"
        //设置请求参数
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        
        ]
        //发送post请求
     
        POST(urlString, parameters: parameters, success: { (_, result) -> Void in
//请求的结果:
//            result =Optional({
//                "access_token" = "2.00LQWEcF0XZdSpef64ea447fIJXwhB";
//                "expires_in" = 144694;
//                "remind_in" = 144694;
//                uid = 5143242251;
//            })
            //需要将结果转成字典 回调
            let dic = result as? [String : AnyObject]
            finished(result: dic, error: nil)
            
            }) { (_, error) -> Void in
                
            finished(result: nil, error: error)
        }
        
        
    }
    //MARK: - 加载用户信息.
    func loadUserInfo(finished: (result:[String : AnyObject]?,error: NSError?)->()){
        //获取AccessToken,判断有值才可以加载
//        if let access_token = RXUserAccount.loadUserAccount()?.access_token{
//            
//            if let uid = RXUserAccount.loadUserAccount()?.uid{
//                //如果uid有值才可以发送请求.
//            }
//        }
//        判断太多
//        守卫:符合条件的会跳过 失败的在 {}中
        guard let access_token = RXUserAccount.loadUserAccount()?.access_token else{
            print("access_token没有值")
            return
        }
        guard let uid = RXUserAccount.loadUserAccount()?.uid else{
            //进来表明uid没有值.
            print("uid没有值")
            return
        }
        //到下面就证明uid 有值.
        // 可以省略baseURL afn会自动加上,
        let urlString = "2/users/show.json"
        //请求参数
        let parameters = [
            "access_token": access_token,
                     "uid": uid
            ]
        //发送请求获取用户数据 
        GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            //结果可以通过准备好的闭包往外面掉.
            
            let dic = result as? [String: AnyObject]
            
            print("result: \(result)")
            //请求成功,往外面回调结果
            
            finished(result: dic, error: nil)
            
            }) { (_,error) -> Void in
                
                finished(result: nil,error: error)
        }
        
        
    }
    //TODO:
    //MARK: - 获取微博数据
    func loadStatus(finished :(result: [String: AnyObject]?,error: NSError?)->()){
        
        
        let urlString = "2/statuses/home_timeline.json"
        //判断access_token是不是有值
        guard let access_token = RXUserAccount.loadUserAccount()?.access_token else{
            
            print("access_token没有值.")
//            //将错误回调出去
//            finished(result: nil, error: nil)
            return
        }
     //设置参数.
        let parameters = ["access_token":access_token]
        
        //发送请求
        GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            //回调结果
            let dic = result as! [String: AnyObject]
            finished(result: dic, error: nil)
            
            }) { (_, error) -> Void in
                //加载失败回调错误信息
                finished(result: nil, error: error)
        }
        
        
        
        
        
        
        
        
    }
    
    
    
    
    
}
